package com.cup.common.encryption;

import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JWTToken {

    /**
     * @param key    私钥
     * @param params map 中 value 转义为 string
     * @return
     * @Title: CreateToken
     * @Description: 创建token
     */
    public static String CreateToken(String key, Map<String, String> params) {
        Algorithm algorithm;
        Builder token;
        String strtoken = "";
        try {
            algorithm = Algorithm.HMAC512(key);
            token = JWT.create();
            for (String pkey : params.keySet()) {
                if (params.get(pkey) == null) {
                    token.withClaim(pkey, "");
                } else {
                    token.withClaim(pkey, params.get(pkey).toString());
                }
            }
            strtoken = token.sign(algorithm);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return strtoken;
    }

    /**
     * @param token
     * @return
     * @Title: decode
     * @Description: decode 返回 payloader 部分, 由于加密时以string, 获取时请用 claims.asString()
     */
    public static Map<String, Claim> decode(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaims();
    }

    /**
     * @param key   私钥
     * @param token
     * @return
     * @Title: verify
     * @Description: 验证token
     */
    public static boolean verify(String key, String token) {
        Algorithm algorithm;
        try {
            algorithm = Algorithm.HMAC512(key);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    
    /**
     * tokenstr 转 map
     * @param tokenStr
     * @return
     * @throws Exception
     */
    public static Map<String, String> getToken(String tokenStr) {
    	
    	Map<String, Claim> claims = JWTToken.decode(tokenStr);
        Map<String, String> userMap = new HashMap<>();
        for (String key : claims.keySet()) {
            userMap.put(key, claims.get(key).asString());
        }
        
		return userMap;
    }
    
}
